package com.sduept.nwld.dataserver.manager.etl;

import com.sduept.cim.model.core.Substation;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.bigdata.fault.common.ETLDAO;
import com.sduept.nwld.dataserver.manager.protection.ProtectOverhaulManager;
import com.sduept.nwld.dataserver.model.daily.OverhaulMsg;
import com.sduept.nwld.dataserver.util.CimUtils;
import com.sduept.utils.BeanUtil;
import com.sduept.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
public class OverhaulMsgETLManager {
	@Autowired
	private SuperDAO dao;
	
	@Autowired
	private ETLDAO eDao;
	@Autowired
	private CimManager cm;
	@Autowired
	private ProtectOverhaulManager overHaulManage;
	
	public  void receiveAndSaveAllData() {
		List<?> list = getAllSourceData();
		receiveAndSave(list);
	}
	public  void receiveAndSavePartData(String date) {
		List<?> list = getAllSourceData(date);
		receiveAndSave(list);
	}
	
	
	public List<?> getAllSourceData(){
		List <?>result = eDao.query("select applicantCompany,content,station_name,actualStartTime,actualEndTime,executiveCondition,done from t_daily_protectoverhaulmag ");
		return result;
	}
	public List<?> getAllSourceData(String date) {
		String sql = "select applicantCompany,content,station_name,actualStartTime,actualEndTime,executiveCondition,done from t_daily_protectoverhaulmag"
				+ " where update_time=";
		List<?> result = eDao.query(sql + "'" + date + "'");
		return result;
	}
	public  void receiveAndSave(List<?> list) {
		ETLDataSave equipmentSave = new ETLDataSave(list);
		equipmentSave.saveToBean();
	}
	/**
	 * 判断s2 是否是s1 的缩写
	 * @param s1
	 * @param s2
	 * @return
	 */
	private  boolean isContain(String s1,String s2){
		char [] stringArr = s2.toCharArray();
		int pos[]=new int[stringArr.length];
		for(int i=0;i<stringArr.length;i++){
			String c = String.valueOf(stringArr[i]);
			if(s1.contains(c)){
				pos[i]=s1.indexOf(c);
				if(i!=0){
					if(pos[i]-pos[i-1]<0){
						return false;
					}
				}
			}else{
				return false;
			}
		}
		return true;
	}
	public class ETLDataSave{
		private List<?> list;
		private Map<String,Substation> map=new HashMap<String,Substation>();
 
		public ETLDataSave(List<?> list) {
			super();
			this.list = list;
			List<Substation> allStations = cm.getAllStations();
			for(Substation sub:allStations){
				if(StringUtils.isNotEmpty(sub.getName())){
					map.put(sub.getName(), sub);
				}
			}
		}
		/**
		 * 根据名字获取变电站对象
		 * @param name
		 * @return
		 */
		private Substation getSubstationByName(String name){
			Substation substation=null;
			substation = map.get(name);
			if(substation==null){
				for(Substation sub:map.values()){
					if(CimUtils.stationNameMatching(name, sub.getName())){
						substation=sub;
						break;
					}
				}
			}
			if(substation==null){
				for(Substation sub:map.values()){
					if(isContain(sub.getName(),name)||isContain(name,sub.getName())){
						substation=sub;
						break;
					}
				}
			}
			return substation;
		}
		public void saveToBean(){
			List<OverhaulMsg> datas = new ArrayList<OverhaulMsg>();
			HashSet<String> sets = new HashSet<String>();//忽略比较的字段
			sets.add("id");
			sets.add("name");
			sets.add("executiveCondition");
			for(Object obj : list){
				Object[] objs = (Object[]) obj;
				OverhaulMsg msg=new OverhaulMsg();
				if(objs[0]!=null){
					msg.setApplicantCompany(objs[0].toString());//申请单位
				}else{
					continue;
				}
				if(objs[1]!=null){
					msg.setContent(objs[1].toString());//检修内容
				}else{
					continue;
				}
				if(objs[2]!=null){
					msg.setStation_name(objs[2].toString());
					Substation substation = getSubstationByName(objs[2].toString());
					if(substation==null){
						Substation substation2 = getSubstationByName(objs[0].toString());
						if(substation2!=null){
							msg.setApplicantCompany(objs[2].toString());
							msg.setStation_name(substation2.getName());
							msg.setStation_id(substation2.getId());
						}
					}else{
						msg.setStation_name(substation.getName());
						msg.setStation_id(substation.getId());
					}
					
				}
				if(objs[3]!=null){
					msg.setStartTime(DateUtil.getDateByString(objs[3].toString(), DateUtil.pattern_ymd));
				}
				if(objs[4]!=null){
					msg.setEndTime(DateUtil.getDateByString(objs[4].toString(), DateUtil.pattern_ymd));
				}
				overHaulManage.updateOverhaulMsgBySatus(msg);
				msg.setId(ObjectId.get().toString());
				boolean isExit=false;
				for(OverhaulMsg over:datas){
					try {
						if(BeanUtil.compareTwoBean(over, msg, sets)){
							isExit=true;
							break;
						}
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
				if(!isExit){
					List<OverhaulMsg> condition = dao.findByCondition(OverhaulMsg.class, "applicantCompany = ? and content=? and station_name=? and station_id=? and startTime=? and endTime=?",
							msg.getApplicantCompany(),msg.getContent(),msg.getStation_name(),msg.getStation_id(),msg.getStartTime(),msg.getEndTime());
					if(condition==null||condition.size()==0)
						datas.add(msg);
				}
			}
			try {
				dao.persistentBatch(OverhaulMsg.class, datas);
				log.info("更新保护检修管理："+datas.size());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
